package cn.iocoder.yudao.module.trade.delivery.api;

import cn.iocoder.yudao.module.api.trade.delivery.ExpressApi;
import cn.iocoder.yudao.module.api.trade.delivery.ExpressApiFactory;
import cn.iocoder.yudao.module.api.trade.delivery.enums.ExpressApiEnum;
import cn.iocoder.yudao.module.trade.framework.ExpressApiProperties;
import lombok.AllArgsConstructor;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 快递接口工厂实现类
 *
 * @author jason
 */
@AllArgsConstructor
public class ExpressApiFactoryImpl implements ExpressApiFactory {

    private final Map<ExpressApiEnum, ExpressApi> clientMap = new ConcurrentHashMap<>(8);

    private final ExpressApiProperties expressApiProperties;
    private final RestTemplate restTemplate;

    @Override
    public ExpressApi getDefaultExpressApi() {
        return getOrCreateExpressApi(expressApiProperties.getClient());
    }

    @Override
    public ExpressApi getOrCreateExpressApi(ExpressApiEnum apiEnum) {
        return clientMap.computeIfAbsent(apiEnum,
                client -> createExpressClient(client, expressApiProperties));
    }

    private ExpressApi createExpressClient(ExpressApiEnum queryProviderEnum,
                                           ExpressApiProperties expressApiProperties) {
        return switch (queryProviderEnum) {
            case KD_NIAO -> new KdNiaoExpressApiImpl(restTemplate, expressApiProperties.getKdNiao());
            case KD_100 -> new Kd100ExpressApiImpl(restTemplate, expressApiProperties.getKd100());
            default -> new NoProvideExpressApiImpl();
        };
    }

}
